angular.module('starter')

    .service('AuthService', function ($q, $http, USER_ROLES, CONSTANT_COMMON, $ionicPopup) {
        var LOCAL_TOKEN_KEY = 'yourTokenKey';
        var username = '';
        var isAuthenticated = false;
        var role = '';
        var authToken;

        function loadUserCredentials() {
            var token = window.localStorage.getItem(LOCAL_TOKEN_KEY);
            if (token) {
                useCredentials(token);
            }
        }

        function storeUserCredentials(token) {
            window.localStorage.setItem(LOCAL_TOKEN_KEY, token);
            useCredentials(token);
        }

        function useCredentials(token) {
            username = token.split('.')[0];
            isAuthenticated = true;
            authToken = token;

            if (username == 'admin') {
                role = USER_ROLES.admin
            }
            if (username == 'user') {
                role = USER_ROLES.public
            }

            // Set the token as header for your requests!
            $http.defaults.headers.common['X-Auth-Token'] = token;
        }

        function destroyUserCredentials() {
            authToken = undefined;
            username = '';
            isAuthenticated = false;
            $http.defaults.headers.common['X-Auth-Token'] = undefined;
            window.localStorage.removeItem(LOCAL_TOKEN_KEY);
        }

        var login = function (name, pw) {
            return $q(function (resolve, reject) {

                var emailLogin = {"email": 'eacdy0000@126.com', "password": '123456'}
                $http.post(CONSTANT_COMMON.url + '/auth/email', emailLogin).then(function (response) {
                        console.log(response.data);

                        if (response.data.success) {
                            // 登录成功
                            storeUserCredentials(name + '.yourServerToken');
                            resolve('Login success.');
                        }
                        else {
                            reject('Login Failed.');
                        }
                    },
                    function (response) {
                        var x = JSON.stringify(response);
                        $ionicPopup.alert({
                            title: '网络异常',
                            template: x
                        });


                        /* var alertPopup = $ionicPopup.alert({
                         title: '网络异常',
                         template: '网络异常，请稍后重试.'
                         });*/
                    });

                /* if ((name == 'admin' && pw == '1') || (name == 'user' && pw == '1')) {
                 // Make a request and receive your auth token from your server
                 storeUserCredentials(name + '.yourServerToken');
                 resolve('Login success.');
                 } else {
                 reject('Login Failed.');
                 }*/


            });
        };

        var logout = function () {
            destroyUserCredentials();
        };

        var isAuthorized = function (authorizedRoles) {
            if (!angular.isArray(authorizedRoles)) {
                authorizedRoles = [authorizedRoles];
            }
            return (isAuthenticated && authorizedRoles.indexOf(role) !== -1);
        };

        loadUserCredentials();

        return {
            login: login,
            logout: logout,
            isAuthorized: isAuthorized,
            isAuthenticated: function () {
                return isAuthenticated;
            },
            username: function () {
                return username;
            },
            role: function () {
                return role;
            }
        };
    })


    .factory('AuthInterceptor', function ($rootScope, $q, AUTH_EVENTS) {
        return {
            responseError: function (response) {
                $rootScope.$broadcast({
                    401: AUTH_EVENTS.notAuthenticated,
                    403: AUTH_EVENTS.notAuthorized
                }[response.status], response);
                return $q.reject(response);
            }
        };
    })

    .config(function ($httpProvider) {
        $httpProvider.interceptors.push('AuthInterceptor');
    });
